/**
 * 
 */
package com.geekteam.geometrychess.handler.event;

import java.util.List;

import com.geekteam.geometrychess.extension.ChessExtension;
import com.geekteam.geometrychess.utils.Code;
import com.geekteam.geometrychess.utils.Commands;
import com.geekteam.geometrychess.utils.Message;
import com.geekteam.geometrychess.utils.Utils;
import com.smartfoxserver.v2.core.ISFSEvent;
import com.smartfoxserver.v2.core.SFSEventParam;
import com.smartfoxserver.v2.entities.Room;
import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.entities.data.ISFSObject;
import com.smartfoxserver.v2.exceptions.SFSException;
import com.smartfoxserver.v2.extensions.BaseServerEventHandler;

/**
 * @author MtRol
 *
 */
public class DisconnectEventHandler extends BaseServerEventHandler{

	@Override
	public void handleServerEvent(ISFSEvent event) throws SFSException {
		Room room = null;
		@SuppressWarnings("unchecked")
		List<Room> joinedRooms = (List<Room>) event.getParameter(SFSEventParam.JOINED_ROOMS);
		
		if(joinedRooms!=null && joinedRooms.size()>0){
			room = joinedRooms.get(0);
		}else{
			return;
		}
		
		if(room ==null)
			return;
		//send command Disconnect to all player in room. 
		User user = (User) event.getParameter(SFSEventParam.USER);
		ISFSObject sfsObject = Utils.toSFSObject(user);
		send(Commands.USER_DISCONNECT, sfsObject, room.getUserList());
		
		if(room.isGame()){
			ChessExtension ext = (ChessExtension) getParentExtension();
			ext.sendPublicError(Code.SERVER_CHAT, Message.USER_DISCONNECT, user.getId(), room.getPlayersList());
		}
	}
	
}
